﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.SignalR.Client;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace IceDog.OTM.Server
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var webHost = CreateWebHostBuilder(args).Build();
            StartSignalR();
            webHost.Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
        private static void StartSignalR()
        {
            Task.Run(() =>
            {
                string host = "localhost:5000";
                string url = $"http://{host}/gameHub";
                var builder = new HubConnectionBuilder();

                builder.WithUrl(url);
                HubConnection connection = builder.Build();
                connection.Closed += async (error) =>
                {
                    await Task.Delay(new Random().Next(1, 5) * 1000);
                    await connection.StartAsync();
                };

                while (connection.State == HubConnectionState.Disconnected)
                {
                    connection.StartAsync().Wait();
                    Task.Delay(2000).Wait();
                }

                int id = 0;

                while (true)
                {
                    connection.SendAsync("AddScore", 1, 999).Wait();
                    Thread.Sleep(5000);
                }
            });
        }
    }
}
